<?php

namespace controller;

/**
 * Klasa rozszerzająca możliwości kontrolera o sprawdzenie czy użytkownik moze korzystać z panelu admina sklepu
 *
 * @author Damian
 */
class Seller extends Controller {

    /**
     *
     * @var \model\TblSeller <p>sprzedawca</p>
     */
    protected $seller;
    public $perPage = 12;

    protected function ShopNotSelected() {
        throw new \model\exceptions\ShopNotSelectedException("aby wejść do panelu administacyjnego sklepu musisz podać jego adres lub zalogować się jako sprzedawca i zostaniesz automatycznie przekierowany");
    }

    public function __construct($options = array()) {

        $this->defaultLayout = "layout/seller";
        parent::__construct($options);
        $router = \library\Registry::get("router");
        //var_dump($router);
        // $this->createLayoutView();
        $session = \library\Registry::get("session");
        if (\library\RequestMethods::get("shop", null, false) == null) {
            $this->ShopNotSelected();
        } else {
            $this->seller = $session->get("seller");
            if ($this->person == null || $this->seller == null) {
                $this->seller = null;
                $session->erase("person");
                $session->erase("seller");
                $session->erase("login");
                $URL = \library\RequestMethods::server("HTTP_HOST") . \library\RequestMethods::server("REDIRECT_URL");
                throw new exceptions\ForbiddenAccessException("dostęp do aderesu {$URL} wymaga zalogwania jako sprzedawca");
            }
            //dodać sprawdzenie innego sklepu!!!!
            //$shopURL = \model\TblShop::
        }
        if ($this->shop == null) {
            $this->redirect("ShopAdmin");
        }
        $Layoutview = $this->getLayoutView();
        $Layoutview->set("action", $router->action);
        $Layoutview->set("controller", $router->controller);
        if ($session->get("login", false)) {
            $this->person = $session->get("login", false);
            $Layoutview->set("logged", true);
            $Layoutview->set("shopName", $this->shop->Name);
            $Layoutview->set("person", $session->get("login"));
        }
        $katalog = APP_PATH . SEPARATOR . "public_html" . SEPARATOR . "img";
        if (!file_exists($katalog . SEPARATOR . substr($this->shop->URL, 0, strlen($this->shop->URL) - 1))) {
            $name = $katalog . SEPARATOR . substr($this->shop->URL, 0, strlen($this->shop->URL) - 1);
            mkdir($name);
            mkdir($name . SEPARATOR . "128px");
            mkdir($name . SEPARATOR . "300px");
            mkdir($name . SEPARATOR . "800px");
        }
        $conversationsCriteria = new \model\Criteria();
        $conversationsCriteria->from(\model\TblConversation::getModel()->getTable())
                ->where(\model\TblConversation::SHOP_ID, "=", $this->shop->ShopID);
        $Conversations = \model\TblConversation::getModel()->all($conversationsCriteria);
        if ($Conversations) {
            $unread = 0;
            foreach ($Conversations as $conv) {
                $messageCountCriteria = new \model\Criteria();
                $messageCountCriteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::CONVERSATION_ID, "=", $conv->ConversationID)
                        ->where(\model\TblAnswer::SEND_BY_CUSTOMER, "=", 1, false, " and ")
                        ->where(\model\TblAnswer::SEEN, "=", 0, false, " and ");
                $unread+= $messageCountCriteria->count();
            }
            $Layoutview->set("unread", $unread);
        }
        //zamówienia
        $newOrdersCriteria = new \model\Criteria();
        $newOrders = $newOrdersCriteria->from(\model\TblOrder::getModel()->getTable())
                        ->where(\model\TblOrder::SHOP_ID, "=", $this->shop->ShopID)
                        ->where(\model\TblOrder::STATUS, "=", "5", false, " and ")->count();
        $Layoutview->set("NewOrders", $newOrders);
        $realizedOrdersCriteria = new \model\Criteria();
        $realizedOrders = $realizedOrdersCriteria->from(\model\TblOrder::getModel()->getTable())
                        ->where(\model\TblOrder::SHOP_ID, "=", $this->shop->ShopID)
                        ->where(\model\TblOrder::STATUS, "=", "1", false, " and ")->count();
        $Layoutview->set("realizedOrders", $realizedOrders);
        //opinie o produktach
        $opinionsCriteria = new \model\Criteria();
        $opinionsCriteria->from(\model\TblOpinion::getModel()->getTable())
                ->where(\model\TblOpinion::MODERATED, "=", "0")
                ->where(\model\TblOpinion::SHOP_ID, "=", $this->shop->ShopID, false, " and ");
        $newOpinions = $opinionsCriteria->count();
        $Layoutview->set("newOpinions", $newOpinions);
        //customers
        $customersCriteria = new \model\Criteria();
        $customersCriteria->from(\model\TblCustomer::getModel()->getTable())
                ->where(\model\TblCustomer::SHOP_ID, "=", $this->shop->ShopID);
        $customers = $customersCriteria->count();
        $Layoutview->set("customers", $customers);
    }

    // private function 

    public function index() {
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Witamy w panelu zarzadzania sklepem");
        $now = new \DateTime("now", new \DateTimeZone("Europe/Warsaw"));
        $month = (\library\RequestMethods::get("month")) ? \library\RequestMethods::get("month") : $now->format("m");
        $year = (\library\RequestMethods::get("year")) ? \library\RequestMethods::get("year") : $now->format("Y");
        $statsID = (\library\RequestMethods::get("id")) ? \library\RequestMethods::get("id") : 1;
        $statsModel = new \model\Stats();
        $stats = $statsModel->getStats($year, $month, $this->shop->ShopID, $statsID);
        $date = new \model\Date($year);
        $monthObj = $date->getMonth($month);
        $names = $statsModel->getNames();
        $view = $this->getActionView();
        $months = $date->getMonths();

        //Ostatnie aktywności
        //komentarze
        $opinionsCriteria = new \model\Criteria();
        $opinionsCriteria->from(\model\TblOpinion::getModel()->getTable())
                ->join(\model\TblCustomer::getModel())
                ->join(\model\TblPerson::getModel())
                ->join(\model\TblProduct::getModel())
                ->order(\model\TblOpinion::ADDITION_DATE, " desc ", \model\TblOpinion::getModel()->getTable())
                ->where(\model\TblOpinion::SHOP_ID, "=", $this->shop->ShopID, \model\TblOpinion::getModel()->getTable());
        $opinions = \model\TblOrder::getModel()->all($opinionsCriteria->limit(30));
        $opinionsDataTable = new \model\DataTable($opinions,true,  \model\TblOpinion::ADDITION_DATE);
        $opinionsTable = $opinionsDataTable->getModelData(true);
        foreach ($opinionsTable as &$opinion){
            $opinion->type=1;//opinia
            $opinion->AdditionDate=  \DateTime::createFromFormat("Y-m-d H:i:s", $opinion->AdditionDate, new \DateTimeZone("Europe/Warsaw"));
        }
        $view->set("opinions",$opinionsTable);
        
        //zamówienia
        $orderCriteria = new \model\Criteria();
        $orderCriteria->from(\model\TblOrder::getModel()->getTable())                
                ->where(\model\TblOrder::SHOP_ID, "=", $this->shop->ShopID, \model\TblOrder::getModel()->getTable())
                ->order(\model\TblOrder::ORDER_DATE, " desc ")
                ->join(\model\TblCustomer::getModel())
                ->join(\model\TblPerson::getModel());
        $orders = \model\TblOrder::getModel()->all($orderCriteria->limit(30));
        $ordersDataTable = new \model\DataTable($orders,true,  \model\TblOrder::ORDER_DATE);
       $ordersTable = $ordersDataTable->getModelData(true);
       foreach ($ordersTable as &$order){
           $order->type=2;//zamówienie
           $order->OrderDate=  \DateTime::createFromFormat("Y-m-d H:i:s", $order->OrderDate, new \DateTimeZone("Europe/Warsaw"));
           $productsCriteria = new \model\Criteria();
           $productsCriteria->from(\model\TblProductOrder::getModel()->getTable())
                   ->join(\model\TblProduct::getModel())
                   ->where(\model\TblProductOrder::ORDER_ID, "=", $order->OrderID);
           $products = new \model\DataTable(\model\TblProductOrder::getModel()->all($productsCriteria));
           $order->Products = $products->getModelData(true);
       }
       $view->set("orders",$ordersTable);
       $LogLoginCriteria = new \model\Criteria();
       $LogLoginCriteria->from(\model\TblLogLogin::getModel()->getTable())
               ->join(\model\TblPerson::getModel(), "all","inner join")
               ->join(\model\TblCustomer::getModel(), "all","inner join")
               ->order(\model\TblLogLogin::LOGIN_DATE, " desc ")
               ->limit(30);
       $logLogin = \model\TblLogLogin::getModel()->all($LogLoginCriteria);
       $logLoginDataTable = new \model\DataTable($logLogin, true, \model\TblLogLogin::LOGIN_DATE);
       $logLoginTable = $logLoginDataTable->getModelData(true);
       foreach ($logLoginTable as &$login){
           $login->type=3;//log_login
           $customerCriteria = new \model\Criteria();
           $customerCriteria->from(\model\TblCustomer::getModel()->getTable(),[\model\TblCustomer::ID=>"CustomerID"])
                   ->where(\model\TblCustomer::PERSON_ID, "=", $login->PersonID->PersonID);
           $login->Customer = $customerCriteria->all()[0]["CustomerID"];
           $login->LoginDate=  \DateTime::createFromFormat("Y-m-d H:i:s", $login->LoginDate, new \DateTimeZone("Europe/Warsaw"));
       }
       $view->set("orders",$ordersTable);
       $LogWatchCriteria = new \model\Criteria();
       $LogWatchCriteria->from(\model\TblLogWatch::getModel()->getTable())               
               ->join(\model\TblCustomer::getModel(), "all")
               ->join(\model\TblPerson::getModel(), "all")
               ->join(\model\TblProduct::getModel())
               ->where(\model\TblLogWatch::CUSTOMER_ID, " is not null", " ", \model\TblLogWatch::getModel()->getTable()," ",false)
               ->order(\model\TblLogWatch::WATCH_DATE, " desc ")
               ->limit(30);
       $logWatch = \model\TblLogLogin::getModel()->all($LogWatchCriteria);
       $logWatchDataTable = new \model\DataTable($logWatch,true, \model\TblLogWatch::WATCH_DATE);
       $logWatchTable = $logWatchDataTable->getModelData(true);
       foreach ($logWatchTable as &$Watch){
           $Watch->type=4;//log_watch
           $Watch->WatchDate=  \DateTime::createFromFormat("Y-m-d H:i:s", $Watch->WatchDate, new \DateTimeZone("Europe/Warsaw"));
       }
       $logCustomer = $logLoginTable+$logWatchTable;
      krsort($logCustomer);
      $view->set("logCustomer",$logCustomer);
       $all = $ordersTable+$opinionsTable+$logCustomer;       
       krsort($all);
       $all = array_slice($all,0,30);
       $view->set("all",$all);
        $view->set("stats", $stats);
        $view->set("names", $names);
        $view->set("month", $monthObj);
        $view->set("months", $months);
        $view->set("statsID", $statsID);
        $view->set("year", $year);
        $this->render();
    }

    //put your code here
}
